//
//  HMOAuthViewController.swift
//  sina
//
//  Created by Kent on 16/9/26.
//  Copyright © 2016年 Ming. All rights reserved.
//

import UIKit
import SVProgressHUD

//App Key：1204741058

//App Secret：ee19337ad62f4d8e94b1f17705505fed

let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

class HMOAuthViewController: UIViewController {

    internal
    
    lazy var webView = UIWebView()
    
    override func loadView() {
        super.loadView()
        
        webView.isOpaque = false
        view = webView
        webView.delegate = self
        
        view.backgroundColor = UIColor.white
        
        setNavBar()
        
        loadoAuthPage()
    }

    func setNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(leftBarBtnClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填写", target: self, action: #selector(rightBarBtnClick))
        
    }
    
    private func loadoAuthPage() {
        
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri)
        
        let req = URLRequest(url: url!)
        
        webView.loadRequest(req)
        
    }
    
    @objc private func leftBarBtnClick() {
        dismiss(animated: true, completion: nil)
    }
    
    func rightBarBtnClick() {
        let string = "document.getElementById('userId').value = 'AppsGiraffe@gmail.com', document.getElementById('passwd').value = 'appsGiraffe2015'"
        webView.stringByEvaluatingJavaScript(from: string)
    }
    
    
}

extension HMOAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.url?.absoluteString ?? ""
        
        let codeFlag = "code="
        
        if urlString.contains(codeFlag) {
            
            let query = request.url?.query ?? ""
            
            let code = (query as NSString).substring(from: codeFlag.characters.count)
            
            HMUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code: code, finished: { (success) in
                
                if !success {

                    return
                }

                NotificationCenter.default.post(name: Notification.Name(KchangeRootViewController), object: "login")
                
            })
     
            return false
        }
        
        return true
    }
    
}














































